﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.WebApp.ViewModel;
using System.Text;

namespace XSTDZ.ERP.WebApp.Models
{
    public class PermissionModel
    {
        /// <summary>
        /// 初始化根结点
        /// </summary>
        /// <returns></returns>
        public PermissionDto InitPermissionRoot()
        {
            PermissionDto permission = new PermissionDto
            {
                Id = XSTDZ.ERP.Infrastructure.SystemConfig.permissionTreeRootId,// Guid.NewGuid(),
                Level = 0,
                Name = XSTDZ.ERP.Infrastructure.SystemConfig.permissionTreeRootName,
                Code="root",
            };
            permission.Controller = permission.Code;
            permission.Action = permission.Code;
            return permission;
        }
        /// <summary>
        /// 绑定权限数据
        /// </summary>
        /// <param name="permissionlst"></param>
        /// <returns></returns>
        public OrgViewModel GetAllPermissions(IEnumerable<PermissionDto> permissionlst, IEnumerable<PermissionDto> uiPermissionlst, IEnumerable<Guid> selectPermissionIds)
        {
            if (permissionlst == null)
            {
                return null;
            }
            var root = InitPermissionRoot();
            OrgViewModel permissionTree = new OrgViewModel
            {
                id = root.Id.ToString(),
                text = root.Name,
                isorg = "1"
            };

            bool hasSelect=false;
            #region 第一级(Action粗粒度没有层级关系)
            foreach (var item in permissionlst)
            {
                #region 选中操作 2013/08/04 edit by chenqiao 
		            if(selectPermissionIds!=null&&selectPermissionIds.Count()>0)
                    {
                        hasSelect = selectPermissionIds.Where(id => id == item.Id).FirstOrDefault()==item.Id;
                    }
	             #endregion
                var childPermission=new OrgViewModel()
                {
                    id = item.Id.ToString(),
                    text = item.Name.ToString(),
                    isorg = "1",
                    ischecked=hasSelect,
                    typename=item.TypeName,
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                };
                permissionTree.children.Add(childPermission);
                //AddUiPermission(uiPermissionlst,childPermission);
                AddUiPermissionNew(uiPermissionlst,selectPermissionIds, childPermission);
            }
            #endregion
            
            return permissionTree;
        }
        bool hasSelect = false;
        public OrgViewModel AddUiPermissionNew(IEnumerable<PermissionDto> uiPermissionlst, IEnumerable<Guid> selectPermissionIds, OrgViewModel root)
        {
            if (uiPermissionlst == null)
            {
                return root;
            }
            var actionResource = uiPermissionlst.Where(p => p.ParentId.ToString() == root.id);

            foreach (var item in actionResource)
            {
                #region 选中操作 2013/08/04 edit by chenqiao
                if (selectPermissionIds != null && selectPermissionIds.Count() > 0)
                {
                    hasSelect = selectPermissionIds.Where(id => id == item.Id).FirstOrDefault() == item.Id;
                }
                #endregion
                root.children.Add(new OrgViewModel()
                {
                    id = item.Id.ToString(),
                    text = item.UiPermission.ImagePath.ToString(), // item.UiPermission.ClientId.ToString(),
                    isorg = "0",
                    ischecked=hasSelect,
                    typename=item.TypeName,
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                });
            }
            return root;
        }
        #region 已过时，不用 2013/8/4 9:50 edit by chenqiao
        public OrgViewModel AddUiPermission(IEnumerable<UiPermissionDto> uiPermissionlst, OrgViewModel root)
        {
            if (uiPermissionlst == null)
            {
                return root;
            }
            var actionResource = uiPermissionlst.Where(p => p.PermissionID.ToString() == root.id);

            foreach (var item in actionResource)
            {
                root.children.Add(new OrgViewModel()
                {
                    id = item.Id.ToString(),
                    text = item.ClientId.ToString(),
                    isorg = "0",
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                });
            }
            return root;
        }
        #endregion
       


        #region 菜单树结点选中操作
        public OrgViewModel GetPermissionSelectHandler(OrgViewModel orgViewModel, IEnumerable<Guid> selectPermissionIds, IEnumerable<Guid> selectUiPermissionIds)
        {
            if (orgViewModel == null || orgViewModel.children.Count == 0)
            {
                return orgViewModel;
            }
            if (selectPermissionIds!=null&&selectPermissionIds.Count() > 0)
            {
                orgViewModel = GetPermissionDtoOfSelect(orgViewModel, selectPermissionIds);
            }
            //if (selectUiPermissionIds != null && selectUiPermissionIds.Count() > 0)
            //{
            //    for (int i = 0; i < orgViewModel.children.Count; i++)
            //    {
            //        orgViewModel.children[i] = GetPermissionDtoOfSelect(orgViewModel.children[i], selectUiPermissionIds);
            //    }
            //}
            return orgViewModel;
        }

        private OrgViewModel GetPermissionDtoOfSelect(OrgViewModel orgViewModel, IEnumerable<Guid> selectPermissionIds)
        { 
            if(orgViewModel==null||orgViewModel.children.Count==0)
            {
                return orgViewModel;
            }

            if (selectPermissionIds != null && selectPermissionIds.Count() > 0)
            {
                var permissions = orgViewModel.children;
                for (int i = 0; i < permissions.Count;i++ )
                {
                    foreach (var id in selectPermissionIds)
                    {
                        if (permissions[i].id == id.ToString())
                        {
                            permissions[i].ischecked = true;
                            break;
                        }
                    }
                }
            }
            return orgViewModel;
        }

        #endregion

        #region 菜单两级结点操作(由于数据库驱动设计失误导致这样操作，否则采用上面的通用型)
         /// <summary>
        /// 绑定权限数据
        /// </summary>
        /// <param name="permissionlst"></param>
        /// <returns></returns>
        public OrgViewModel GetPermissions(IList<PermissionDto> permissionlst, IList<UiPermissionModel> uiPermissionlst)
        {
            if (permissionlst == null)
            {
                return null;
            }
            var root = InitPermissionRoot();
            OrgViewModel permissionTree = new OrgViewModel
            {
                id = root.Id.ToString(),
                text = root.Name,
                isorg = "1"
            };

            #region 第一级(Action粗粒度没有层级关系)
            foreach (var item in permissionlst)
            {
                var childPermission=new OrgViewModel()
                {
                    id = item.Id.ToString(),
                    text = item.Name.ToString(),
                    isorg = "1",
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                };
                permissionTree.children.Add(childPermission);
                AddSimpleUiPermission(uiPermissionlst, childPermission);
            }
            #endregion
            
            return permissionTree;
        }
        private OrgViewModel AddSimpleUiPermission(IList<UiPermissionModel> uiPermissionlst, OrgViewModel root)
        {
            if (uiPermissionlst == null)
            {
                return root;
            }
            var actionResource = uiPermissionlst.Where(p => p.ParentId.ToString() == root.id);

            foreach (var item in actionResource)
            {
                root.children.Add(new OrgViewModel()
                {
                    id = item.Id.ToString(),
                    text = item.Name.ToString(),
                    isorg = "0",
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                });
            }
            return root;
        }
        #endregion

        #region 三级，第一级写死，这个是在没办法情况下直接对用户授权

        public string GetUserPermissionJson(IList<OrgViewModel> lst, IEnumerable<Guid> selectPermissionIds)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{'Rows':[");
            
            if (lst != null && lst.Count > 0)
            { 
                var firstLevel=lst.Where(t=>t.isorg=="1").ToList();
                var tempT = @"{ id: '{0}', name:'{1}'{0}},";
                foreach (var f in firstLevel)
                {
                    var str = string.Format(tempT,f.id.ToString(),f.text,"{0}");
                    if (f.children.Count() > 0)
                    {
                        str = string.Format(str, "children: [{0}]");
                        foreach (var s in f.children)
                        {
                            str = string.Format(str, s.id.ToString(), s.text, "{0}");
                            if (s.children.Count > 0)
                            {
                                str = string.Format(str, s.id.ToString(), s.text, "{0}");
                            }
                        }
                    }
                    else
                    {
                        str = string.Format(tempT,"");
                    }
                    
                }
            }
            sb.Append("] }");

            return "";
        }
        private string GetTempString(IList<OrgViewModel> lst)
        {
            if (lst != null && lst.Count > 0)
            {
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
                return target = ",children: [" + target + "]";
            }
            return "";
        }

         /// <summary>
        /// 绑定权限数据
        /// </summary>
        /// <param name="permissionlst"></param>
        /// <returns></returns>
        public IList<OrgViewModel> GetUserPermissions(IList<PermissionDto> permissionlst, IList<UiPermissionModel> uiPermissionlst, IEnumerable<Guid> selectPermissionIds)
        {
            if (permissionlst == null)
            {
                return null;
            }
            IList<OrgViewModel> permissionTree = new List<OrgViewModel>();
            //var root = InitPermissionRoot();
            //OrgViewModel permissionTree = new OrgViewModel
            //{
            //    id = root.Id.ToString(),
            //    text = root.Name,
            //    isorg = "1"
            //};
            #region 第一级(Action粗粒度没有层级关系)
            var firstLevel = permissionlst.Select(t => t.TypeName).Distinct().ToList();
            foreach (var item in firstLevel)
            {
                var childPermission = new OrgViewModel()
                {
                    id = item.ToString(),
                    text = item.Substring(1,item.Length-1),
                    isorg = "-1",
                    typename = item.ToString(),
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                };
                permissionTree.Add(childPermission);
            }
            #endregion
            #region 第二级(Action粗粒度没有层级关系)
            foreach (var first in permissionTree)
            {
               
                foreach (var item in permissionlst)
                {
                    #region 选中操作 2013/08/04 edit by chenqiao
                    if (selectPermissionIds != null && selectPermissionIds.Count() > 0)
                    {
                        hasSelect = selectPermissionIds.Where(id => id == item.Id).FirstOrDefault() == item.Id;
                    }
                    #endregion

                    if (first.id == item.TypeName)
                    {
                        var childPermission = new OrgViewModel()
                        {
                            id = item.Id.ToString(),
                            text = item.Name.ToString(),
                            ischecked = hasSelect,
                            typename = item.Name.ToString(),
                            isorg = "1",
                            icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                        };
                        first.children.Add(childPermission);
                        AddUserSimpleUiPermission(uiPermissionlst,selectPermissionIds, childPermission);
                    }
                }
            }
            #endregion
            
            return permissionTree;
        }
        private OrgViewModel AddUserSimpleUiPermission(IList<UiPermissionModel> uiPermissionlst, IEnumerable<Guid> selectPermissionIds, OrgViewModel root)
        {
            if (uiPermissionlst == null)
            {
                return root;
            }
            var actionResource = uiPermissionlst.Where(p => p.ParentId.ToString() == root.id);

            foreach (var item in actionResource)
            {
                #region 选中操作 2013/08/04 edit by chenqiao
                if (selectPermissionIds != null && selectPermissionIds.Count() > 0)
                {
                    hasSelect = selectPermissionIds.Where(id => id == item.Id).FirstOrDefault() == item.Id;
                }
                #endregion
                root.children.Add(new OrgViewModel()
                {

                    id = item.Id.ToString(),
                    text = item.Name.ToString(),
                    ischecked = hasSelect,
                    typename = item.Name.ToString(),
                    isorg = "0",
                    icon = @XSTDZ.ERP.Infrastructure.SystemConfig.deptIcon
                });
            }
            return root;
        }
      
        #endregion
    }

    public class UiPermissionModel
    {
        public Guid ParentId { get; set; }
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
}